<template>
  <el-dialog 
    :visible.sync="isShow" 
    destroy-on-close
    title="部门编辑"
    width="400px"
    top="60px"
    :close-on-click-modal="false">
    <el-form ref="form" :model="fields" :rules="rules" label-width="80px">
      <el-form-item label="上级部门" prop="pid">
        <el-cascader
          v-model="fields.pid"
          style="width:100%"
          size="small"
          :options="parents"
          :props="{
            label: 'name',
            value: 'id',
            children: 'childrens',
            checkStrictly: true,
            emitPath: false,
          }"
          clearable
          placeholder="请选择上级部门"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model.trim="fields.name"
          autocomplete="off"
          size="small"
          placeholder="请输入部门名称"
          maxlength="64"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="loading" size="mini" @click="closePage"
        >取消</el-button
      >
       <el-button
        :loading="loading"
        type="primary"
        size="mini"
        @click="onOkBtnClick"
        >保存</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { saveOrUpdate, get } from '@/api/dept'

export default {
  props: {
    value: {
      type: Object,
      default: () => Object.create({})
    }
  },
  data() {
    return {
      isShow: true,
      fields: {},
      parents: [],
      rules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
      }
    }
  },
  watch: {
    isShow: function() {
      this.$emit('input', null)
    }
  },
  created() {
    this.get(this.value.id || null)
  },
  methods: {
    onOkBtnClick() {
      this.submitForm()
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        valid &&
          saveOrUpdate(this.fields)
            .then(() => {
              this.isShow = false
              this.$parent.onSearchBtnClick()
            })
            .catch(() => {})
      })
    },
    resetForm() {
      this.$refs['form'].resetFields()
    },
    async get(id) {
      const res = await get(id)
      this.fields = res
      this.parents = [{ name: '一级部门', id: '0' }].concat(res.resouces || [])
      if (!this.fields.pid && this.parents.length) {
        this.fields.pid = this.parents[0].id
      }
    },
    closePage() {
      this.isShow = false
      this.resetForm()
    },
  }
}
</script>
